import 'dart:async';
import 'dart:math';
import 'dart:typed_data';

import 'package:flutter_spectrum/fft/fftea.dart';
import 'package:flutter_spectrum/flutter_spectrum_method_channel.dart';

import 'flutter_spectrum_platform_interface.dart';

class FlutterSpectrum {
  ///播放音频
  Future<void> startPlay({
    required String filePath,
    required EventHandler onEvent,
    required EventHandler playCompleted,
    required EventHandler onError,
  }) async {
    FlutterSpectrumPlatform.instance.listenPcm(onEvent, onError);
    FlutterSpectrumPlatform.instance.onPlayCompleted(playCompleted);
    await FlutterSpectrumPlatform.instance.startPlay(filePath);
  }

  ///停止播放
  Future<void> stopPlay() async {
    await FlutterSpectrumPlatform.instance.stopPlay();
  }

  ///归一化
  List<double> normalize(List<double> magnitudes) {
    double maxMagnitude = magnitudes.reduce(max);
    return magnitudes.map((m) => m / maxMagnitude).toList();
  }

  /// 生成汉明窗（Hamming Window）
  List<double> applyHammingWindow(List<double> buffer) {
    int N = buffer.length;
    List<double> windowedBuffer = List.filled(N, 0.0);
    for (int n = 0; n < N; n++) {
      windowedBuffer[n] = buffer[n] * (0.54 - 0.46 * cos(2 * pi * n / (N - 1)));
    }
    return windowedBuffer;
  }

  ///快速傅里叶
  List<double> performFFT(List<double> buffer) {
    int N = buffer.length;
    var fft = FFT(N);
    var spectrum = fft.realFft(buffer);
    List<double> magnitudes = [];
    for (int i = 0; i <= N ~/ 2; i++) {
      Float64x2 complex = spectrum[i];
      double real = complex.x;
      double imaginary = complex.y;
      magnitudes.add(sqrt(real * real + imaginary * imaginary));
    }
    return magnitudes;
  }
}
